home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 11513 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.3 KB  |  56 lines

  1. Newsgroups: comp.lang.c++
  2. Path: driftwood.cray.com!jvb
  3. From: jvb@cray.com (Jeff Boyd)
  4. Subject: overload + operator question
  5. Message-ID: <1996Mar14.133124.12847@driftwood.cray.com>
  6. Nntp-Posting-Host: hickory024
  7. Organization: Cray Research, Inc.
  8. Date: 14 Mar 96 13:31:24 CST
  9.  
  10. I have a question regarding an overloaded + (or *) operator.  The code segment
  11. below gives the following message, as expected:
  12.  
  13. "coord-add.C", line 38: Error: The operation "int + coord" is illegal.
  14.  
  15. but by making the class + class operator a 'friend' all compiles fine and gives
  16. expected results.  Why?  Happens with: g++, Sparc C++, Cfront, Cray.
  17. Please send any answers to me as I don't have regular news access. Thanks.
  18.  
  19. Code:
  20.  
  21. #include <iostream.h>
  22.  
  23. class coord{
  24.   int x;
  25. public:
  26.   coord():x(0){}
  27.   coord(int i):x(i){}
  28.   void get_x(int &i){i = x;}
  29. // by making next operator a 'friend', then an operation
  30. // such as:  'int + coord' becomes legal
  31.   coord operator+(coord ob2);  // ob + ob
  32. };
  33.  
  34. // overload + relative to coord class
  35. coord coord::operator + (coord ob2)
  36. {
  37.   coord temp;
  38.   temp.x = x + ob2.x;
  39.   return temp;
  40. }
  41.  
  42.  
  43. main()
  44. {
  45.   coord o1(10),o2(3),o3;
  46.   int x;
  47.   o3 = o2 + 100;
  48. // will be flagged as 'illegal' unless friend ob + ob defined:
  49.   o3 = 100 + o2;
  50.   o3.get_x(x);
  51. }
  52.  
  53. ------
  54. Jeff
  55. jvb@cray.com
  56.